<!-- src/components/MiniChart.vue -->
<template>
  <div class="mini-chart-wrapper">
    <div class="mini-chart-container">
      <svg :width="chartWidth" :height="chartHeight" class="mini-chart">
        <!-- 定义渐变，用于阴影 -->
        <defs>
          <linearGradient :id="gradientId" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" :stop-color="color" stop-opacity="0.3" />
            <stop offset="100%" :stop-color="color" stop-opacity="0" />
          </linearGradient>
        </defs>

        <!-- 绘制阴影区域 (平滑) -->
        <path
            v-if="smoothShadowPath"
            :d="smoothShadowPath"
            :fill="`url(#${gradientId})`"
            stroke="none"
        />

        <!-- 绘制平滑折线 -->
        <path
            v-if="smoothLinePath"
            :d="smoothLinePath"
            fill="none"
            :stroke="color"
            :stroke-width="strokeWidth"
            stroke-linecap="round"
            stroke-linejoin="round"
        />

        <!-- 透明覆盖层，用于捕获鼠标事件，并直接绑定事件 -->
        <rect
            x="0"
            y="0"
            :width="chartWidth"
            :height="chartHeight"
            fill="transparent"
            @mouseenter="showTooltip = true"
            @mouseleave="showTooltip = false"
        />
      </svg>

      <!-- 悬停弹框 -->
      <div v-if="showTooltip" class="tooltip">
        {{ displayValue }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue';

const props = defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  current: {
    type: [Number, String],
    default: null
  },
  color: {
    type: String,
    default: '#409EFF'
  }
});

const showTooltip = ref(false);

const gradientId = ref('');
onMounted(() => {
  // 生成唯一ID，避免在同一页面多个图表时冲突
  gradientId.value = `mini-chart-gradient-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
});

const chartWidth = 100;
const chartHeight = 30;
const strokeWidth = 1.5;

// --- 平滑曲线计算辅助函数 ---
const generateSmoothLinePath = (points) => {
  if (points.length === 0) return '';
  if (points.length === 1) {
    return `M ${points[0].x},${points[0].y} L ${chartWidth},${points[0].y}`;
  }

  let d = `M ${points[0].x},${points[0].y}`;
  for (let i = 1; i < points.length; i++) {
    const xc = (points[i].x + points[i - 1].x) / 2;
    const yc = (points[i].y + points[i - 1].y) / 2;
    d += ` Q ${points[i - 1].x},${points[i - 1].y} ${xc},${yc}`;
  }
  // 使用 T 命令完成到最后一个点的平滑连接
  d += ` T ${points[points.length - 1].x},${points[points.length - 1].y}`;
  return d;
};

const generateSmoothAreaPath = (points) => {
  if (points.length === 0) return '';
  if (points.length === 1) {
    return `M ${points[0].x},${points[0].y} L ${chartWidth},${points[0].y} L ${chartWidth},${chartHeight} L 0,${chartHeight} Z`;
  }

  let topPath = `M ${points[0].x},${points[0].y}`;
  for (let i = 1; i < points.length; i++) {
    const xc = (points[i].x + points[i - 1].x) / 2;
    const yc = (points[i].y + points[i - 1].y) / 2;
    topPath += ` Q ${points[i - 1].x},${points[i - 1].y} ${xc},${yc}`;
  }
  topPath += ` T ${points[points.length - 1].x},${points[points.length - 1].y}`;

  // 连接到图表底部并闭合路径
  let bottomPath = ` L ${chartWidth},${chartHeight} L 0,${chartHeight} Z`; // Z 自动连接回起始点

  return topPath + bottomPath;
};
// --- 平滑曲线计算辅助函数结束 ---


const dataPoints = computed(() => {
  const validData = props.data.filter(val => typeof val === 'number' && !isNaN(val));
  if (validData.length === 0) return [];

  const len = validData.length;
  // 假设数据范围是 0-100，可以根据实际需求调整
  const maxVal = 100;
  const minVal = 0;
  const range = maxVal - minVal;

  return validData.map((val, index) => {
    // 计算 x 坐标 (均匀分布)
    const x = (index / (len - 1)) * chartWidth;
    // 防止由于浮点数计算导致的微小越界
    const clampedX = Math.max(0, Math.min(chartWidth, x));

    // 计算 y 坐标 (反转Y轴，SVG的y=0在顶部)
    const y = chartHeight - ((val - minVal) / (range || 1)) * chartHeight;
    // 防止由于浮点数计算导致的微小越界
    const clampedY = Math.max(0, Math.min(chartHeight, y));

    return { x: clampedX, y: clampedY };
  });
});

const smoothLinePath = computed(() => {
  return generateSmoothLinePath(dataPoints.value);
});

const smoothShadowPath = computed(() => {
  return generateSmoothAreaPath(dataPoints.value);
});

const displayValue = computed(() => {
  if (typeof props.current === 'number' && !isNaN(props.current)) {
    return props.current.toFixed(2) + '%';
  }
  // 如果 props.current 是 null, undefined, 或非数字字符串，则显示 --
  return '--';
});
</script>

<style scoped>
/* 包裹容器，用于定位 tooltip */
.mini-chart-wrapper {
  position: relative;
  display: inline-block; /* 或 block, 根据布局需要 */
  width: fit-content; /* 或具体宽度 */
}

/* 图表容器 */
.mini-chart-container {
  position: relative; /* 为 tooltip 定位提供上下文 */
  width: v-bind('chartWidth + "px"'); /* 绑定到 JS 变量 */
  height: v-bind('chartHeight + "px"');
  cursor: pointer;
}

.mini-chart {
  display: block;
  width: 100%;
  height: 100%;
}

/* 悬停弹框样式 */
.tooltip {
  position: absolute;
  top: calc(100% + 5px); /* 位于 SVG 下方 5px */
  left: 50%;
  transform: translateX(-50%); /* 水平居中 */
  background-color: #333;
  color: white;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 1000;
  pointer-events: none; /* 防止弹框干扰鼠标事件 */
  border: 1px solid #555;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  /* 可选：添加小箭头 */
  /*
  &::after {
    content: '';
    position: absolute;
    top: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 5px solid #333;
  }
  */
}
</style>



